import { defineStore } from 'pinia'
import { getUserConversations, getSessions } from '@/api/history.js'

export const useChatStore = defineStore('chat', {
  state: () => ({
    // 对话历史列表
    chatHistory: [],
    // 当前活跃的对话ID
    currentChatId: null,
    // 当前活跃对话对象
    currentChat: null,
    // 最大保存的对话数量
    maxChatCount: 50,
    // 本地存储和远程同步状态
    isLoading: false,
    lastSyncTime: null
  }),

  getters: {
    // 获取当前对话
    getCurrentChat: (state) => {
      return state.currentChat || state.chatHistory.find(chat => chat.id === state.currentChatId)
    },

    // 获取对话数量
    getChatCount: (state) => {
      return state.chatHistory.length
    },

    // 按时间排序的对话历史
    getSortedChatHistory: (state) => {
      return [...state.chatHistory].sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
    }
  },

  actions: {
    // 创建新对话
    createNewChat(title = null) {
      const newChat = {
        id: 'chat_' + Date.now(),
        title: title || '新对话',
        messages: [],
        sessionId: null,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        model: 'deepseek-chat'
      }

      this.chatHistory.unshift(newChat)
      this.currentChatId = newChat.id
      this.currentChat = newChat
      
      // 限制对话数量
      if (this.chatHistory.length > this.maxChatCount) {
        this.chatHistory = this.chatHistory.slice(0, this.maxChatCount)
      }

      this.saveToStorage()
      return newChat
    },

    // 添加消息到当前对话
    addMessage(role, content, sessionId = null) {
      const chat = this.getCurrentChat
      if (!chat) {
        // 如果没有当前对话，创建一个新的
        this.createNewChat()
      }

      const message = {
        id: 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
        role, // 'user' 或 'assistant'
        content,
        timestamp: new Date().toISOString()
      }

      const currentChat = this.getCurrentChat
      currentChat.messages.push(message)
      currentChat.updatedAt = new Date().toISOString()

      // 如果是第一条用户消息，用它作为对话标题
      if (role === 'user' && currentChat.messages.filter(m => m.role === 'user').length === 1) {
        currentChat.title = content.length > 20 ? content.substring(0, 20) + '...' : content
      }

      // 更新sessionId
      if (sessionId) {
        currentChat.sessionId = sessionId
      }

      this.saveToStorage()
      return message
    },

    // 切换到指定对话
    switchToChat(chatId) {
      this.currentChatId = chatId
      this.currentChat = this.chatHistory.find(chat => chat.id === chatId)
      this.saveToStorage()
    },

    // 删除指定对话
    deleteChat(chatId) {
      const index = this.chatHistory.findIndex(chat => chat.id === chatId)
      if (index > -1) {
        this.chatHistory.splice(index, 1)
        
        // 如果删除的是当前对话，切换到最新的对话
        if (this.currentChatId === chatId) {
          if (this.chatHistory.length > 0) {
            this.switchToChat(this.chatHistory[0].id)
          } else {
            this.currentChatId = null
            this.currentChat = null
          }
        }
      }
      
      this.saveToStorage()
    },

    // 清空所有对话
    clearAllChats() {
      this.chatHistory = []
      this.currentChatId = null
      this.currentChat = null
      this.saveToStorage()
    },

    // 更新对话标题
    updateChatTitle(chatId, newTitle) {
      const chat = this.chatHistory.find(chat => chat.id === chatId)
      if (chat) {
        chat.title = newTitle
        chat.updatedAt = new Date().toISOString()
        this.saveToStorage()
      }
    },

    // 保存到本地存储
    saveToStorage() {
      try {
        const data = {
          chatHistory: this.chatHistory,
          currentChatId: this.currentChatId,
          lastSyncTime: this.lastSyncTime
        }
        uni.setStorageSync('chat_store_data', JSON.stringify(data))
      } catch (error) {
        console.error('保存聊天数据到本地存储失败:', error)
      }
    },

    // 从本地存储加载
    loadFromStorage() {
      try {
        const dataStr = uni.getStorageSync('chat_store_data')
        if (dataStr) {
          const data = JSON.parse(dataStr)
          this.chatHistory = data.chatHistory || []
          this.currentChatId = data.currentChatId || null
          this.lastSyncTime = data.lastSyncTime || null
          
          // 恢复当前对话对象
          if (this.currentChatId) {
            this.currentChat = this.chatHistory.find(chat => chat.id === this.currentChatId)
          }
        }
      } catch (error) {
        console.error('从本地存储加载聊天数据失败:', error)
        // 如果加载失败，创建默认对话
        this.createNewChat()
      }
    },

    // 从服务器同步对话历史
    async syncFromServer() {
      if (this.isLoading) return

      this.isLoading = true
      try {
        // 获取服务器上的对话记录
        const response = await getUserConversations({
          page: 1,
          pageSize: 5  // 限制只获取5条数据
        })

        if (response && response.data) {
          const serverChats = response.data.conversations || response.data.records || []
          
          // 将服务器数据转换为本地格式
          const formattedChats = serverChats.map(serverChat => {
            return {
              id: serverChat.sessionId || 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
              title: this.generateChatTitle(serverChat.messages || []),
              messages: (serverChat.messages || []).map(msg => ({
                id: msg.id || 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
                role: msg.role,
                content: msg.content || msg.text || '',
                timestamp: msg.timestamp || msg.createdAt || new Date().toISOString()
              })),
              sessionId: serverChat.sessionId,
              createdAt: serverChat.createdAt || new Date().toISOString(),
              updatedAt: serverChat.updatedAt || new Date().toISOString(),
              model: serverChat.model || 'deepseek-chat'
            }
          })

          // 合并本地和服务器数据，去重
          const mergedChats = this.mergeChats(this.chatHistory, formattedChats)
          this.chatHistory = mergedChats.slice(0, 5)  // 限制只保留5条数据
          
          this.lastSyncTime = new Date().toISOString()
          this.saveToStorage()
        }
      } catch (error) {
        console.error('从服务器同步对话历史失败:', error)
      } finally {
        this.isLoading = false
      }
    },

    // 合并本地和服务器聊天记录
    mergeChats(localChats, serverChats) {
      const chatMap = new Map()
      
      // 添加本地聊天记录
      localChats.forEach(chat => {
        chatMap.set(chat.sessionId || chat.id, chat)
      })
      
      // 添加服务器聊天记录，如果存在则合并
      serverChats.forEach(serverChat => {
        const key = serverChat.sessionId || serverChat.id
        const existingChat = chatMap.get(key)
        
        if (existingChat) {
          // 合并消息，保留最新的
          const allMessages = [...existingChat.messages, ...serverChat.messages]
          const uniqueMessages = allMessages.filter((msg, index, arr) => 
            arr.findIndex(m => m.id === msg.id) === index
          ).sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
          
          existingChat.messages = uniqueMessages
          existingChat.updatedAt = serverChat.updatedAt > existingChat.updatedAt ? 
            serverChat.updatedAt : existingChat.updatedAt
        } else {
          chatMap.set(key, serverChat)
        }
      })
      
      return Array.from(chatMap.values()).sort((a, b) => 
        new Date(b.updatedAt) - new Date(a.updatedAt)
      )
    },

    // 生成对话标题
    generateChatTitle(messages) {
      if (!messages || messages.length === 0) {
        return '新对话'
      }
      
      const firstUserMessage = messages.find(msg => msg.role === 'user')
      if (firstUserMessage) {
        const content = firstUserMessage.content || firstUserMessage.text || ''
        return content.length > 20 ? content.substring(0, 20) + '...' : content
      }
      
      return '新对话'
    },

    // 获取当前对话的消息数量
    getCurrentChatMessageCount() {
      const chat = this.getCurrentChat
      return chat ? chat.messages.length : 0
    },

    // 检查是否需要同步
    shouldSync() {
      if (!this.lastSyncTime) return true
      
      const now = new Date()
      const lastSync = new Date(this.lastSyncTime)
      const diffMinutes = (now - lastSync) / (1000 * 60)
      
      return diffMinutes > 30 // 30分钟同步一次
    },

    // 清理空对话（温和版本，只在有空对话时才清理）
    removeEmptyChatsIfAny() {
      const initialCount = this.chatHistory.length
      this.chatHistory = this.chatHistory.filter(chat => {
        // 保留有消息的对话，或者有标题的对话
        return (chat.messages && chat.messages.length > 0) || 
               (chat.title && chat.title.trim() !== '' && chat.title !== '新对话')
      })
      
      const removedCount = initialCount - this.chatHistory.length
      if (removedCount > 0) {
        console.log(`温和清理了 ${removedCount} 个空对话`)
        this.saveToStorage()
      }
      
      return removedCount
    },

    // 强制清理空对话
    cleanEmptyChats() {
      const initialCount = this.chatHistory.length
      this.chatHistory = this.chatHistory.filter(chat => {
        // 保留有消息的对话，或者有标题的对话
        return (chat.messages && chat.messages.length > 0) || 
               (chat.title && chat.title.trim() !== '' && chat.title !== '新对话')
      })
      
      const removedCount = initialCount - this.chatHistory.length
      if (removedCount > 0) {
        console.log(`强制清理了 ${removedCount} 个空对话`)
        this.saveToStorage()
      }
      
      return removedCount
    }
  }
}) 